package com.wenhao.leetcode.medium;

/**
 * 题目：https://leetcode-cn.com/problems/spiral-matrix-ii/
 * 螺旋矩阵 II
 * @author Wenhao Tong
 * @Description
 * @create 2021-06-30 12:44
 */
public class LeetCode59 {
    public static void main(String[] args) {
        LeetCode59 leetCode59 = new LeetCode59();
        int[][] matrix = leetCode59.generateMatrix(5);
        for (int[] row : matrix) {
            for (int i : row) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int top = 0;
        int bottom = n - 1;
        int left = 0;
        int right = n - 1;
        int num = 1;
        while (top <= bottom && left <= right) {
            for (int i = left;i <= right;i++) {
                matrix[top][i] = num++;
            }
            ++top;
            // 因为是方阵，因此这一个判断其实是多余的
//            if (++top > bottom) {
//                return matrix;
//            }
            for (int i = top;i <= bottom;i++) {
                matrix[i][right] = num++;
            }
            --right;
//            if (--right < left) {
//                return  matrix;
//            }
            for (int i = right;i >= left;i--) {
                matrix[bottom][i] = num++;
            }
            --bottom;
            for (int i = bottom;i >= top;i--) {
                matrix[i][left] = num++;
            }
            ++left;
        }
        return matrix;
    }
}
